#define _CRT_SECURE_NO_WARNINGS 1
#include "Stack.h"

void StackInit(Stack* ps)
{
	assert(ps);
	ps->capacity = 4;
	StackDataType* ptr = (StackDataType*)malloc(sizeof(StackDataType)*ps->capacity);
	if (ptr == NULL)
	{
		perror("malloc fail");
		return;
	}
	ps->data = ptr;
	ptr = NULL;
	ps->top = 0;
}

void StackDestroy(Stack* ps)
{
	assert(ps);
	free(ps->data);
	ps->data = NULL;
	ps->capacity = ps->top = 0;
}

int StackSize(Stack* ps)
{
	assert(ps);
	return ps->top;
}

bool StackEmpty(Stack* ps)
{
	assert(ps);
	return ps->top == 0;
}

void StackPush(Stack* ps, StackDataType x)
{
	assert(ps);
	if (ps->top == ps->capacity)
	{
		StackDataType* ptr = (StackDataType*)realloc(ps->data, sizeof(StackDataType)* (ps->capacity)*2);
		if (ptr == NULL)
		{
			perror("realloc fail");
			return;
		}
		else
		{
			ps->data = ptr;
			ptr = NULL;
			ps->capacity *= 2;
		}
	}

	ps->data[ps->top] = x;
	ps->top++;
}

void StackPop(Stack* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));

	ps->top--;
}

StackDataType StackTop(Stack* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));

	return ps->data[ps->top - 1];
}